// src/utils/request.ts
import axios, { AxiosError } from 'axios'
import type {
    AxiosInstance,
    AxiosResponse,
    InternalAxiosRequestConfig,
} from 'axios'

import { ElMessage } from 'element-plus'
import useUserStore from '@/stores/modules/user.ts'
import router from '@/router'

// 定义后端统一返回格式（可按你实际接口调整）
interface ResponseData<T = any> {
    code: number
    msg: string
    data: T
}

// 创建 axios 实例
const request: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API, // 从 .env 文件中读取
    timeout: 8000, // 超时时间
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
    },
})

request.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const userStore = useUserStore()
        if (userStore.accessToken) {
            config.headers = config.headers || {}
            config.headers.Authorization = `Bearer ${userStore.accessToken}`
        }
        return config
    },
    (error: AxiosError) => Promise.reject(error)
)


// 响应拦截器
request.interceptors.response.use(
    (response: AxiosResponse<ResponseData>) => {
        const { code, data, msg } = response.data

        if (code === 200 || code === 0) {
            return data
        }

        ElMessage.error(msg || '请求出错')
        return Promise.reject(new Error(msg || 'Error'))
    },
    (error: AxiosError) => {
        let message = '网络错误，请稍后重试'

        if (error.response) {
            const status = error.response.status
            switch (status) {
                case 400:
                    message = '请求参数错误'
                    break
                case 401:
                    message = '登录状态已过期，请重新登录'
                    const userStore = useUserStore()
                    // userStore.logout()
                    router.push('/login')
                    break
                case 403:
                    message = '无访问权限'
                    break
                case 404:
                    message = '请求地址不存在'
                    break
                case 500:
                    message = '服务器内部错误,请联系管理员'
                    break
            }
        } else if (error.message.includes('timeout')) {
            message = '请求超时，请检查网络'
        }

        ElMessage.error(message)
        return Promise.reject(error)
    },
)

export default request
